import { Form } from "../base/form";
import { adminStore } from "@b/store";
import { ElInput } from "element-plus";
import { h } from "vue";
import type { RuleItem } from "async-validator";
import type { interCustomize } from "../base/type";


export class Login extends Form<interfaceLogin> {
    constructor() {
        super()
        this.label_width = "6em"
        this.data.username = localStorage.getItem('phone') || ''
    }
    setLabels() {
        const vPhone: RuleItem[] = [{ type: 'string', required: true, message: '请填写账号' }]
        const vPassword: RuleItem[] = [{ type: 'string', required: true, message: '请填写密码' }]
        this.rule = {
            username: vPhone,
            password: vPassword
        }
        this.setItem({
            username: {
                prop: 'username',
                label: '账号',
                type: 'text',
                rule: Form.getVantRule(vPhone)
            },
            password: {
                prop: 'password',
                label: '密码',
                rule: Form.getVantRule(vPassword),
                type: 'password'
            },
            // verifyCode: {
            //     prop: 'verifyCode',
            //     label: '验证码',
            //     type: 'customize',
            //     vform: () => h('div', {})
            // }
        }, this.labels)
    }
    init() {
        this.setLabels()
    }
    async onLogin() {
        const res = await adminStore().login(this.data)
        // if (!res) this.getCaptcha()
    }
    async getCaptcha() {
        const label = this.labels.verifyCode as interCustomize<interfaceLogin, 'verifyCode'>
        if (!label) return
        const res: interfaceCaptcha = await this.request('/admin/base/open/captcha?height=50&width=150&color=%232c3142', { method: 'GET' })
        if (!res.captchaId) return
        this.data.captchaId = res.captchaId
        label.vform = ({ prop, data, value }) => h('div', {
            style: {
                display: 'flex',
                alignItems: 'center'
            }
        }, [h(ElInput, {
            modelValue: value, onInput: (inputValue: string) => {
                data[prop] = inputValue
            }, onKeydown: (e: any) => {
                if (e.key === 'Enter' || e.key === 'NumpadEnter') {
                    this.onLogin()
                }
            }
        }), h('img', {
            style: {
                height: '50px',
                width: '150px',
                cursor: 'pointer',
                marginLeft: '10px'
            },
            onClick: () => {
                this.getCaptcha()
            },
            src: res.data
        })])
    }
}